package org.example.serve;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;

@Service
public class ImageStorageService {
    @Value("${uva.images.directory}")
    private String imageDirectory;

    private static final int MAX_IMAGES = 20;
    private static final String PREFIX = "imageUVA";

    @PostConstruct
    public void init() throws IOException {
        Path path = Paths.get(imageDirectory);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }
    }

    public synchronized void saveUVAImage(byte[] imageData) throws IOException {
        File[] existingFiles = getSortedUVAImages();

        // 删除超出限制的旧图片
        if (existingFiles.length >= MAX_IMAGES) {
            int filesToDelete = existingFiles.length - MAX_IMAGES + 1;
            for (int i = 0; i < filesToDelete; i++) {
                Files.delete(existingFiles[i].toPath());
            }
            existingFiles = getSortedUVAImages(); // 重新获取文件列表
        }

        // 确定新文件编号
        int newNumber = 1;
        if (existingFiles.length > 0) {
            String lastName = existingFiles[existingFiles.length - 1].getName();
            newNumber = extractNumber(lastName) + 1;
        }

        // 保存新图片
        String newFileName = PREFIX + newNumber + ".jpg";
        Path newFilePath = Paths.get(imageDirectory, newFileName);
        Files.write(newFilePath, imageData);

        // 重新编号所有文件
        renumberFiles();
    }

    private File[] getSortedUVAImages() {
        File dir = new File(imageDirectory);
        File[] files = dir.listFiles((d, name) -> name.startsWith(PREFIX) && name.endsWith(".jpg"));

        if (files == null) {
            return new File[0];
        }

        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File f1, File f2) {
                return Integer.compare(extractNumber(f1.getName()), extractNumber(f2.getName()));
            }
        });

        return files;
    }

    private int extractNumber(String fileName) {
        try {
            String numStr = fileName.substring(PREFIX.length(), fileName.lastIndexOf('.'));
            return Integer.parseInt(numStr);
        } catch (Exception e) {
            return 0;
        }
    }

    private void renumberFiles() throws IOException {
        File[] files = getSortedUVAImages();

        // 创建临时目录
        Path tempDir = Paths.get(imageDirectory, "temp");
        if (!Files.exists(tempDir)) {
            Files.createDirectory(tempDir);
        }

        // 移动文件到临时目录
        for (File file : files) {
            Path source = file.toPath();
            Path tempDest = tempDir.resolve(source.getFileName());
            Files.move(source, tempDest);
        }

        // 从临时目录移回并重命名
        File[] tempFiles = tempDir.toFile().listFiles();
        if (tempFiles != null) {
            Arrays.sort(tempFiles, new Comparator<File>() {
                @Override
                public int compare(File f1, File f2) {
                    return extractNumber(f1.getName()) - extractNumber(f2.getName());
                }
            });

            int newNumber = 1;
            for (File tempFile : tempFiles) {
                String newName = PREFIX + newNumber++ + ".jpg";
                Files.move(tempFile.toPath(), Paths.get(imageDirectory, newName));
            }
        }

        // 删除临时目录
        Files.delete(tempDir);
    }
}